package com.ojoin.ojoin.eb_spider.service.impl;

import com.ojoin.ojoin.eb_spider.service.WebDriveBaseService;
import com.ojoin.ojoin.eb_spider.service.WebDriverService;
import com.ojoin.ojoin.eb_spider.utils.Config;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.supplyloan_core.web.domain.CatchDataStartMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Service
public abstract class WebDriveBaseServiceImpl implements
        WebDriveBaseService {

    private static Logger log = LoggerFactory
            .getLogger(WebDriveBaseServiceImpl.class);

    /**
     * 数据抓取driver
     */
    public final static int verifycodeRetryCount = 3;

    protected ThreadLocal<Map> tm = new ThreadLocal<>();

    @Autowired
    @Qualifier("chrome")
    private WebDriverService webDriver;

    public WebDriverService getWebDriver() {
        return webDriver;
    }

    public void setWebDriver(WebDriverService webDriver) {
        this.webDriver = webDriver;
    }


    public String initDownloadDir(String platFrom,String userName) {

        String mapping_download_dir = System.getProperties().getProperty("user.home")
                + File.separator + "Downloads" + File.separator
                + platFrom
                + userName
                + File.separator + TimeUtils.getCurDateString();

        LogUtils.info(log, "下载路径download.dir 映射目录-->" + mapping_download_dir);

        tm.get().put(Config.DOWNLOAD,mapping_download_dir);
        return mapping_download_dir;
    }

    @Override
    public void init() {
        Map map = new HashMap();
        tm.set(map);
    }

    @Override
    public boolean prepareCatchData(String cathType,String platFrom,String userName) throws BusinessException, Exception {
        String download = initDownloadDir(platFrom,userName);

        if (cathType.equals(
                CatchDataStartMessage.LOCALHOST)) {
            this.getWebDriver().initWebDriver(download);
        } else {
            this.getWebDriver().initWebDriver(download);
            //this.getWebDriver().initRemoteWebDriver(dowmload);
        }


        return true;
    }

    @Override
    public boolean LoginByUserInfo(String baseUrl, String username, String password) throws Exception {
        return false;
    }

    @Override
    public void closeCatchData()
            throws BusinessException {
        this.getWebDriver().close();
    }

    @Override
    public String getLoginPassword(String pwd) {
        return pwd;
    }


}
